/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年5月23日
 */
package com.massyframework.beanskin.service.serialize;

import java.io.IOException;

import com.massyframework.beanskin.ModuleNotFoundException;

/**
 * {@link Serializer}序列化器,提供对象的序列化和反序列化能力.
 * <p>
 * 序列化器能提供在多类加载器情况下，支持模块实例的序列化和反序列化，
 * 不同对象的反序列化过程，需要动态的切换不同模块类加载器，才能确保反序列化过程的成功。
 * @author huangkh
 */
public interface Serializer {

	/**
	 * 对{@code target}执行序列化
	 * @param target {@link Object},目标对象实例
	 * @return {@link byte}数组
	 */
	byte[] serial(Object target) throws IOException;
	
	/**
	 * 将<code>bytes</code>反序列化对象
	 * @param bytes 对象序列化的字节数组
	 * @return {@link T},对象实例，可能返回null.
	 */
	Object deserial(byte[] bytes) throws IOException, ClassNotFoundException, ModuleNotFoundException;
	
	/**
	 * 将{@code target}进行反序列化，并按{@cpde requiredType}类型返回反序化后的对象
	 * @param bytes 对象序列化的字节数组
	 * @param requiredType 要求返回的类型，可以是反序列化后对象的类型，也可以是其父类、接口类型等
	 * @return {@link T},对象实例，可能返回null.
	 */
	default <T> T deserial(byte[] bytes, Class<T> requireType) throws IOException, ClassNotFoundException, ModuleNotFoundException{
		Object result = this.deserial(bytes);
		if (result == null) return null;
		if (requireType.isAssignableFrom(result.getClass())) {
			return requireType.cast(result);
		}
		return null;
	}
}
